package cn.hr.controller;

import cn.hr.pojo.Dictionary;
import cn.hr.pojo.Post;
import cn.hr.pojo.Resume;
import cn.hr.service.DictionaryService;
import cn.hr.service.PostService;
import cn.hr.service.ResumeService;
import cn.hr.service.SysUserService;
import cn.hr.utils.Constants;
import com.alibaba.fastjson.JSON;
import com.mysql.cj.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 简历信息控制器
 * @author MO
 *
 */
@Controller
@RequestMapping("/sys/resume")
public class ResumeController {
	private Logger logger = LoggerFactory.getLogger(ResumeController.class);
	@Resource
	private ResumeService resumeService;

	@Resource
	private DictionaryService dictionaryService;
	@Resource
	private PostService postService;
	@Resource
	private SysUserService userService;


	//简历列表查询
	@RequestMapping("/updAjax")
	@ResponseBody
	public String upPost(Resume resume) {
		try {
			if (resumeService.update(resume)){
				return "true";
            }
		} catch (Exception e) {
			e.printStackTrace();
			return "false";
		}
		return "false";
	}

	@RequestMapping("/show")
	public String show(@RequestParam(value = "attr",required = false)String attr,Model model) {
		try {
			model.addAttribute("resumeStatus", dictionaryService.selectAllByTypeName("RESUME_TYPE"));
			model.addAttribute("attr", attr);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return "resume/resumeList";
	}

	@RequestMapping(value = "/list")//, method = RequestMethod.POST)
	public String recrtList(@RequestParam(required = false) Map m, Model model) {
		Integer pageNo = 1;
		//List<Dictionary> resumeStatus=null;
		try {
			if (m.get("pageNo") != null) {
				pageNo = Integer.parseInt((String) m.get("pageNo"));
			}
			//resumeStatus=dictionaryService.selectAllByTypeName("RESUME_TYPE");

			//if (model.containsAttribute(""))
			model.addAttribute("pageInfo", resumeService.findListByCondition(m, pageNo));
			model.addAttribute("attr",m.get("attr"));
			model.addAttribute("resumeStatus",dictionaryService.selectAllByTypeName("RESUME_TYPE"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "resume/resumeShow";
	}


	//职位发布登记
	@RequestMapping("/regShow")
	public String regShow(Model model) {
		try {
			model.addAttribute("rtypes", dictionaryService.selectAllByTypeName("RECRUIT_TYPE"));
			model.addAttribute("edtypes", dictionaryService.selectAllByTypeName("EDUCATION_TYPE"));
			model.addAttribute("resume", new Resume());
			model.addAttribute("postType", new Dictionary());
			model.addAttribute("post", new Post());
			model.addAttribute("attr", "reg");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return "resume/resumeAU";
	}

	@RequestMapping(value = "/regSave", method = RequestMethod.POST)
	public String regSave(Resume resume, Model model, @RequestParam("affix")MultipartFile file, HttpSession session, HttpServletRequest request) {
		try {
			if (!file.isEmpty()){
				//上传附件
				String fileName =file.getOriginalFilename(); //获取文件名
				logger.info("---------简历附件上传--------- fileName : "+fileName);
				//String path ="D:\\Temp\\test"+Constants.BASEPATH;
				logger.info("---------简历附件上传路径--------- path : "+Constants.BASEPATH);
				File affix =new File(Constants.BASEPATH,fileName);
				if(!affix.exists()){
					affix.getParentFile().mkdirs();
					affix.createNewFile();
				}
				/*
				File dir = new File(path );
				if(!dir.exists()){ //判断文件父目录是否存在
					dir.mkdir();
					//dest.createNewFile();
				}*/
				file.transferTo(affix); //保存文件
				String downloadLink = request.getContextPath()+File.separator+"static"+File.separator+"uploadfiles"+File.separator+fileName;
				logger.info("---------简历附件下载路径--------- downloadLink : "+downloadLink);
				resume.setAffixName(fileName);
				resume.setAffixPath(Constants.BASEPATH+File.separator+fileName);
				resume.setDownloadLink(downloadLink);
			}
			if (resumeService.insert(resume)) {
				return "redirect:/sys/resume/show";
			}
			model.addAttribute(Constants.SYS_MESSAGE, "添加失败!");
		} catch (Exception e) {
			model.addAttribute(Constants.SYS_MESSAGE, "添加失败!");
			e.printStackTrace();
		}
		return "redirect:/sys/resume/regShow";
	}

	@RequestMapping("/delfile")
	@ResponseBody
	public  String delfile(@RequestParam("id")Integer id){
		Map<String,Object> result =new HashMap<>();
		if (id==null)result.put("result","failed");
		else {
			try {
				if (resumeService.delAffix(id)){
					result.put("result","success");
				}else {
					result.put("result","failed");
				}
			} catch (Exception e) {
				result.put("result","failed");
				e.printStackTrace();
			}
		}
		return JSON.toJSONString(result);
	}


	//文件下载相关代码
	@RequestMapping("/affix/download")
	public String downloadFile(@RequestParam("fileName")String fileName,HttpServletRequest request, HttpServletResponse response) {
		if (fileName != null) {
			//设置文件路径
			//String path ="D:\\Temp\\test"+Constants.BASEPATH;
			File file = new File(Constants.BASEPATH , fileName);
			if (file.exists()) {
				response.setContentType("application/force-download");// 设置强制下载不打开
				response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
				byte[] buffer = new byte[1024];
				FileInputStream fis = null;
				BufferedInputStream bis = null;
				try {
					fis = new FileInputStream(file);
					bis = new BufferedInputStream(fis);
					OutputStream os = response.getOutputStream();
					int i = bis.read(buffer);
					while (i != -1) {
						os.write(buffer, 0, i);
						i = bis.read(buffer);
					}
					System.out.println("success");
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					if (bis != null) {
						try {
							bis.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					if (fis != null) {
						try {
							fis.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		return null;
	}


	//修改发布职位登记
	@RequestMapping("/updShow")
	public String postUpdShow(@RequestParam("id") String id,@RequestParam(value = "view",required = false) String view,@RequestParam(value = "cz",required = false) String cz, Model model) {
		Resume resume =null;
		Dictionary postType =null;
		List<Dictionary> rtypes=null;
		List<Dictionary> edtypes=null;
		Post post =null;
		try {
			resume=resumeService.get(Integer.parseInt(id));
			rtypes= dictionaryService.selectAllByTypeName("RECRUIT_TYPE");
			edtypes=dictionaryService.selectAllByTypeName("EDUCATION_TYPE");
			if (resume!=null) {
				if (resume.getPostId() != null) {
					post = postService.get(resume.getPostId());
					postType = dictionaryService.get("POST_TYPE", post.getSort());
				} else {
					post = new Post();
					postType = new Dictionary();
				}
				if (view!=null&&view.equals("ierg")) {
					model.addAttribute("restatus", dictionaryService.get("RESUME_TYPE", resume.getStatus()).getValueName());
					if (resume.getOneSide() != null)
						model.addAttribute("oneSide", userService.get(resume.getOneSide()).getUserName());
					if (resume.getBiplanar() != null)
						model.addAttribute("biplanar", userService.get(resume.getBiplanar()).getUserName());
					if (resume.getThreeSide() != null)
						model.addAttribute("threeSide", userService.get(resume.getThreeSide()).getUserName());
					if (resume.getHirePeople() != null)
						model.addAttribute("hirePeople", userService.get(resume.getHirePeople()).getUserName());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute("resume", resume);
		model.addAttribute("postType", postType);
		model.addAttribute("post", post);
		model.addAttribute("attr", "upd");
		model.addAttribute("view", view);
		model.addAttribute("cz", cz);
		model.addAttribute("rtypes",rtypes);
		model.addAttribute("edtypes", edtypes);
		if (!StringUtils.isNullOrEmpty(view))return "resume/resumeView";
		return "resume/resumeAU";
	}

	@RequestMapping(value = "/updSave", method = RequestMethod.POST)
	public String updSave(Resume resume, Model model, @RequestParam(value = "affix",required = false)MultipartFile file,@RequestParam(value = "attr",required = false) String attr, HttpServletRequest request) {
		try {
			if (file!=null&&!file.isEmpty()){
				String fileName =file.getOriginalFilename(); //获取文件名
				logger.info("--------- 修改 简历附件上传--------- fileName : "+fileName);
				//String path ="D:\\Temp\\test"+Constants.BASEPATH;
				logger.info("--------- 修改 简历附件上传路径--------- path : "+Constants.BASEPATH);
				File affix =new File(Constants.BASEPATH,fileName);
				if(!affix.exists()){
					affix.getParentFile().mkdirs();
					affix.createNewFile();
				}
				file.transferTo(affix); //保存文件
				String downloadLink = request.getContextPath()+File.separator+"static"+File.separator+"uploadfiles"+File.separator+fileName;
				logger.info("---------简历附件下载路径--------- downloadLink : "+downloadLink);
				resume.setAffixName(fileName);
				resume.setAffixPath(Constants.BASEPATH+File.separator+fileName);
				resume.setDownloadLink(downloadLink);
			}
			if (resumeService.update(resume)) {
				if(attr!=null&&attr.equals("interview"))return "redirect:/sys/resume/show?attr=interview";
				if(attr!=null&&attr.equals("employ"))return "redirect:/sys/resume/show?attr=employ";
				return "redirect:/sys/resume/show";
			}
			model.addAttribute(Constants.SYS_MESSAGE, "修改失败!");
		} catch (Exception e) {
			model.addAttribute(Constants.SYS_MESSAGE, "修改失败!");
			e.printStackTrace();
		}
		if(attr!=null&&attr.equals("interview"))return "redirect:/sys/resume/updShow?id="+resume.getId()+"&view=ierg&cz=ms";
		if(attr!=null&&attr.equals("employ"))return "redirect:/sys/resume/updShow?id="+resume.getId()+"&view=ierg&cz=ly";
		return "redirect:/sys/resume/updShow?id="+resume.getId();
	}

	@RequestMapping(value = "/del")
	public String postDel(@RequestParam("id") Integer id, Model model,@RequestParam(value = "attr",required = false)String attr) {
		try {
			if (resumeService.delete(id)){
				model.addAttribute(Constants.SYS_MESSAGE,"删除成功!");
				if(attr!=null&&attr.equals("interview"))return "redirect:/sys/resume/show?attr=interview";
				return "redirect:/sys/resume/show";
            }else {
				model.addAttribute(Constants.SYS_MESSAGE,"删除失败!");
			}
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute(Constants.SYS_MESSAGE,"删除失败!");
		}
		return "redirect:/sys/resume/show";
	}

}